var request = require('request-promise');
const mingo = require('../common/mongoapi')
const { setQuery } = require('../common/common')
const { H5 } = require('./variables.js');
const { appid, secret, grant_type1 } = H5;
let grant_type = grant_type1;
const getAuth = async (code, ctx, next) => {
    let queryString = setQuery({ code, appid, secret, grant_type });
    const opt = {
        method: 'GET',
        json: true,
        url: 'https://api.weixin.qq.com/sns/oauth2/access_token?' + queryString
    };
    let result = await request(opt);

    let access_token = result.access_token;
    let $openid = result.openid;
    let lang = 'zh_CN';
    let queryString2 = setQuery({ access_token, openid: $openid, lang });
    const opt2 = {
        method: 'GET',
        json: true,
        url: 'https://api.weixin.qq.com/sns/userinfo?' + queryString2
    };
    let result2 = await request(opt2);

    mingo.findOne('users', result2.openid, (data) => {
        if (data == null) {
            mingo.insert('users', result2, () => { });
        } else {
        }
    })
    return result2.openid || '';
}

module.exports = getAuth